#include <stdio.h>
char get_choice(void);
char get_first(void);
float get_float(void);
float add(float a, float b);
float sub(float a, float b);
float multi(float a, float b);
float divide(float a, float b);
int main(void) {
    int choice;
    float f_num = 0;
    float s_num = 0;

    while ((choice = get_choice()) != 'q')
    {
        switch (choice) {
            case 'a':
                printf("Enter first number: ");
                f_num = get_float();
                printf("Enter second number: ");
                s_num = get_float();
                printf("%.2f + %.2f = %.2f\n", f_num, s_num, add(f_num, s_num));
                break;
            case 's':
                printf("Enter first number: ");
                f_num = get_float();
                printf("Enter second number: ");
                s_num = get_float();
                printf("%.2f - %.2f = %.2f\n", f_num, s_num, sub(f_num, s_num));
                break;
            case 'm':
                printf("Enter first number: ");
                f_num = get_float();
                printf("Enter second number: ");
                s_num = get_float();
                printf("%.2f * %.2f = %.2f\n", f_num, s_num, multi(f_num, s_num));
                break;
            case 'd':
                printf("Enter first number: ");
                f_num = get_float();
                printf("Enter second number: ");
                s_num = get_float();
                while (s_num == 0)
                {
                    printf("Enter a number than 0: ");
                    s_num = get_float();
                }
                printf("%.2f / %.2f = %.2f\n", f_num, s_num, divide(f_num, s_num));
                break;
            default:
                printf("Program error!\n");
                break;
        }
        getchar(); // 消耗掉那个 \n
    }
    printf("Bye!\n");

    return 0;
}

char get_choice(void)
{
    int ch;

    printf("Enter the operation of your choice:\n");
    printf("a. add          s. subtract\n");
    printf("m. multiply     d. divide\n");
    printf("q. quit\n");
    ch = get_first();
    while (ch != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q')
    {
        printf("Please respond with a, s, m ,d or q.\n");
        ch = get_first();
    }

    return ch;
}

char get_first(void)
{
    char ch;

    ch = getchar();
    while (getchar() != '\n')
        continue;

    return ch;
}

float get_float(void)
{
    float input;
    char ch;

    while (scanf("%f", &input) != 1)
    {
        while ((ch = getchar()) != '\n')
            putchar(ch);
        printf(" is not a number.\n Please enter a number, such as 2.5, -1.78E8, or 3: ");
    }

    return input;
}

float add(float a, float b)
{
    return a + b;
}

float sub(float a, float b)
{
    return a - b;
}

float multi(float a, float b)
{
    return a * b;
}

float divide(float a, float b)
{
    return a / b;
}